/**
 * 处理所有以/product/*开头请求的路由器
 */
const express = require("express");
const pool = require("../pool");
let router = express.Router();
module.exports = router;
// 查询所有商品的信息
router.get("/", (req, res, next) => {
  let sql = "SELECT * from product";
  pool.query(sql, (err, result) => {
    if (err) {
      next(err);
      return;
    }
    res.json(result);
  });
});
//根据cateid查询同一类型所有商品的信息
router.get("/list", (req, res, next) => {
  let cateid = req.query.cateid;
  let sql = "SELECT * FROM  product where cateid=? ORDER BY pid";
  pool.query(sql, cateid, (err, result) => {
    if (err) {
      next(err);
      return;
    }
    res.json(result);
  });
});
//查询pid查询单个商品的所有信息
router.get("/details", (req, res, next) => {
  let pid = req.query.pid;
  // Es7写法
  (async function() {
    var output = {};
    await Promise.all([
      new Promise((resolve, reject) => {
        let sql = "SELECT * FROM  product where pid=?";
        pool.query(sql, pid, (err, result) => {
          if (err) {
            next(err);
            return;
          }
          output.details = result;
          resolve();
        });
      }),
      new Promise((resolve, reject) => {
        let sql = "SELECT * FROM  pic where pid=? ORDER BY id";
        pool.query(sql, pid, (err, result) => {
          if (err) {
            next(err);
            return;
          }
          output.pics = result;
          resolve();
        });
      })
    ]);
    //   .then(() => {
    //   res.json(output)
    // })
    res.json(output);
  })();
});
//查询商品分类信息
router.get('/category', (req, res, next) => { 
  let sql = "SELECT * FROM category"
  pool.query(sql, (err, result) => { 
    if (err) { 
      next(err)
      return
    }
    res.json(result)
  })
})
